package com.YCH.behavior.service.impl;

import com.YCH.behavior.service.AppPublicArticleBehaviorService;
import com.YCH.model.article.dtos.AppPublicArticleDto;
import com.YCH.model.article.pojos.*;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbArticleConfigMapper;
import com.YCH.model.mappers.app.TbArticleContentMapper;
import com.YCH.model.mappers.app.TbArticleMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.utils.common.Html2Text;
import com.YCH.utils.common.ImgFromEditor;
import com.YCH.utils.common.ZipUtils;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
@Log4j2
@SuppressWarnings("all")
public class AppPublicArticleBehaviorServiceImpl implements AppPublicArticleBehaviorService {
    @Autowired
    TbArticleMapper tbArticleMapper;
    @Autowired
    TbArticleContentMapper tbArticleContentMapper;
    @Autowired
    TbArticleConfigMapper tbArticleConfigMapper;
    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult UserArticlePublic(AppPublicArticleDto dto) {
        // *****************开启事务******************
        // 1.获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if (user == null) {
            return ResponseResult.errorResult(200, "用户未登录");
        }
        Long id = user.getId();
        // 2.数据转换
        // 2.1从数组中获取元素,转换成字符串，以空格分割
        String tags= StringUtils.join(dto.getTag(), " ");
        // 2.2获取图片地址们
        List<String> imgStr = null;
        try{
            imgStr = ImgFromEditor.getImgStr(dto.getContent());
        }catch  (NullPointerException e){
            log.log(Level.ERROR,"富文本没有图片内容"+e.getStackTrace());
        }
        String imgs = StringUtils.join(imgStr," ");
        // 2.3去除富文本标签
        String content = Html2Text.getContent(dto.getContent());
        // 2.4截取前60个字符
        Integer contentLength = content.length();
        content = content.substring(0, contentLength >= 60 ? 60 : contentLength);
        // 2.5压缩文本内容
        String gzip = ZipUtils.gzip(dto.getContent());
        // 3封装TbArticle对象
        TbArticle tbArticle= new TbArticle();
        TbUser tbUser = new TbUser();
        tbUser.setId(id);
        tbArticle.setUser(tbUser);
        tbArticle.setTag(tags);
        tbArticle.setTitle(dto.getTitle());
        tbArticle.setImage(imgs);
        tbArticle.setPartContent(content);
        tbArticle.setCategoryId(dto.getCategoryId());
        tbArticle.setCreatTime(new Date());
        // 3.1 将文章信息存储到数据库
        Integer integer;
        if(dto.getCountyId()!=null){
            tbArticle.setProvinceId(dto.getProvinceId());
            tbArticle.setCityId(dto.getCityId());
            tbArticle.setCountyId(dto.getCountyId());
            integer = tbArticleMapper.insertHasLocation(tbArticle);
        }else {
            integer = tbArticleMapper.insertNoLocation(tbArticle);
        }
        // 3.2 如果integer<1,就返回插入失败
        if(integer<1){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 4 获取刚刚插入的文章id
        Long articleId = tbArticleMapper.selectIdByUserIdLimitOne(id);
        // 5 在tb_articleContent插入文章内容
        TbArticleContent tbArticleContent = new TbArticleContent();
        tbArticleContent.setArticleId(articleId);
        tbArticleContent.setContent(gzip);
        Integer insert = tbArticleContentMapper.insert(tbArticleContent);
        // 5.1 如果integer<1,就返回插入失败
        if(insert<1){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 5.2 获取刚刚插入文章内容的id（tb_articleContent中的id）
        Long articleContentId = tbArticleContentMapper.selectByArticleId(articleId).getId();
        // 6 在tb_article更新文章内容
        TbArticleFlag tbArticleFlag = new TbArticleFlag();
        tbArticleFlag.setId(1);
        tbArticle.setFlag(tbArticleFlag);
        TbArticleContent tbArticleContent1 = new TbArticleContent();
        tbArticleContent1.setId(articleContentId.longValue());
        tbArticle.setContent(tbArticleContent1);
        tbArticle.setId(articleId);
        Long integer1 = tbArticleMapper.updateFlagIdAndContentId(tbArticle);
        if(integer1<1){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 7 在tb_articleConfig插入文章配置
        TbArticleConfig tbArticleConfig = new TbArticleConfig();
        tbArticleConfig.setArticleId(articleId);
        tbArticleConfig.setIsComment(true);
        tbArticleConfig.setIsForward(true);
        // 在此处控制文章是否上下架
        tbArticleConfig.setIsDown(false);
        tbArticleConfig.setIsDelete(false);
        tbArticleConfig.setIsDraft(false);
        tbArticleConfig.setIsCreation(dto.isCreation());
        tbArticleConfig.setIsReprint(dto.isReprint());
        tbArticleConfig.setIsPublic(dto.isPublic());
        Integer integer2 = tbArticleConfigMapper.insertConfig(tbArticleConfig);
        if(integer2<1){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
